package it.i118.jindice;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * User: sciovante
 * Date: 23/10/13
 * Time: 16.51
 */
public class Table {

    static HashMap<Class, Table> tableMap = new HashMap<Class, Table>();

    public static Table get(Class key) {
        Table table = tableMap.get(key);
        if (table == null) {
            table = new Table(key);
            tableMap.put(key, table);
        }
        return table;
    }

    private final Class beanClass;
    private final HashMap<String, Index> indexMap = new HashMap<String, Index>();

    private Table(Class beanClass) {
        this.beanClass = beanClass;
        Field[] fields = beanClass.getFields();

        for (Field field : fields) {
            if (field.isAnnotationPresent(Annotation.Index.class)) {
                Index index = new Index(field);
                indexMap.put(field.getName(), index);
            }

//            if (field.isAnnotationPresent(Annotation.PrimaryKey.class)) {
//                if (primaryKey != null) {
//                    throw new RuntimeException("Annotation.PrimaryKey duplicata");
//                }
//                primaryKey = field;
//            }
        }

//        if (primaryKey == null) {
//            throw new RuntimeException("Annotation.PrimaryKey non definita");
//        }
    }

    public Class getBeanClass() {
        return beanClass;
    }

    public Index getIndex(String name) {
        return indexMap.get(name);
    }

    public Index[] getIndexList() {
        Collection<Index> lov = indexMap.values();
        return lov.toArray(new Index[lov.size()]);
    }
}
